package controller

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/smartwalle/alipay/v3"
	"go.uber.org/zap"
	"net/http"
	"order_bff/appconfig"
	"order_bff/order_proto"
	"order_bff/pkg"
)

// 生成支付链接
func Alipay(c *gin.Context) {
	orderSn := c.PostForm("order_sn")
	if orderSn == "" {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "订单编号不能为空",
			"data": nil,
		})
		return
	}
	comment := pkg.Comment()
	detail, err := comment.OrderDetail(context.Background(), &order_proto.OrderDetailRequest{OrderSn: orderSn})
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "查询订单详情失败",
			"data": nil,
		})
		return
	}
	client, err := alipay.New(appconfig.AppConf.AlipayConfig.AppId, appconfig.AppConf.AlipayConfig.PrivateKey, false)
	if err != nil {
		fmt.Println(err)
		return
	}
	//totalAmount := strconv.FormatFloat(float64(detail.Price), 'f', 0, 10)
	var p = alipay.TradeWapPay{}
	p.NotifyURL = "http://46008c7.r7.cpolar.top/re_back"
	p.ReturnURL = "http://127.0.0.1:8888/return"
	p.Subject = "商品"
	p.OutTradeNo = detail.OrderSn
	p.TotalAmount = "100"
	p.ProductCode = "QUICK_WAP_WAY"

	url, err := client.TradeWapPay(p)
	if err != nil {
		fmt.Println(err)
	}

	// 这个 payURL 即是用于打开支付宝支付页面的 URL，可将输出的内容复制，到浏览器中访问该 URL 即可打开支付页面。
	var payURL = url.String()
	fmt.Println(payURL)
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "请支付",
		"data": payURL,
	})

	//time.Sleep(10 * time.Minute)
	//_, err = comment.DeleteOrder(context.Background(), &order_proto.DeleteOrderRequest{OrderSn: orderSn})
	//if err != nil {
	//	c.JSON(http.StatusNotFound, gin.H{
	//		"code": -1,
	//		"msg":  "删除订单失败",
	//		"data": nil,
	//	})
	//	return
	//}
	//c.JSON(http.StatusOK, gin.H{
	//	"code": 0,
	//	"msg":  "删除订单成功",
	//	"data": nil,
	//})
}

func Return(c *gin.Context) {
	orderSn := c.Query("out_trade_no")
	if orderSn == "" {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "订单编号不能为空",
			"data": nil,
		})
		return
	}
	comment := pkg.Comment()
	detail, err := comment.OrderDetail(context.Background(), &order_proto.OrderDetailRequest{OrderSn: orderSn})
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{
			"code": -1,
			"msg":  "查询订单详情失败",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "查询订单详情成功",
		"data": detail,
	})
}
func ReBack(c *gin.Context) {
	orderSn := c.PostForm("out_trade_no")
	status := c.PostForm("trade_status")
	tradeNo := c.PostForm("trade_no")
	comment := pkg.Comment()
	if status == "TRADE_SUCCESS" {
		_, err := comment.UpdateOrder(context.Background(), &order_proto.UpdateOrderRequest{
			OrderSn: orderSn,
			PayType: 1,
			TradeNo: tradeNo,
			Status:  status,
		})
		zap.S().Info(err)
	} else {
		zap.S().Info("订单支付失败")
	}

}
